<?php

namespace app\backend\controllers;


use app\backend\common\AdminBaseController;
use app\backend\models\ArticleClassModel;
use app\backend\models\ArticleModel;
use app\backend\task\PushArticle;
use app\task\lib\TaskHandle;
use lib\helper\error;
use lib\Tool\Tools;

class ArticleController extends AdminBaseController
{
    public function actionList()
    {
        $ArticleModel = new ArticleModel();
        $data         = $ArticleModel->getArticleByHot();
        $this->assign('data', ['article_list' => $data]);
        return $this->display('article/list');
    }

    public function actionAdd()
    {
       $post = Tools::My()->request()->post();
       if (!empty($post)){
           PushArticle::$tree['param'] = $post;
           PushArticle::$tree['delay'] = 5;
           TaskHandle::addTask(new PushArticle(),'push_article');
           $resTask = TaskHandle::toTask();
           if ($resTask){
               error::_plainError(['message' => '添加任务成功'.PushArticle::$tree['delay'].'S后自动生成']);
           }
           error::_plainError(['message' => '添加失败']);
       }
       $ArticleClassModel = new ArticleClassModel();
       $data = $ArticleClassModel->getArticleClass();
       $this->assign('data',['class_list'=>$data]);
       return $this->display('article/add');
    }

    public function actionEdit()
    {
        $post = Tools::My()->request()->post();
        $get  = Tools::My()->request()->get();
        if (!empty($post) && !empty($get)) {
            PushArticle::$tree['param'] = $post;
            $post['article_id'] = $get['article_id'];
            PushArticle::$tree['delay'] = 10;
            TaskHandle::addTask(new PushArticle(),'push_article_edit');
            $resTask = TaskHandle::toTask();
            if ($resTask){
                error::_plainError(['message' => '添加任务成功'.PushArticle::$tree['delay'].'S后自动修改']);
            }
            error::_plainError(['message' => '修改失败']);
        }
        $data = ArticleModel::find()->where([['=', 'article_id', $get['article_id']]])->one();
        $this->assign('article_info', $data[0]);
        return $this->display('article/edit');
    }

    public function actionDelOrOn()
    {
        $get = Tools::My()->request()->get();
        $code = ArticleModel::find()->where([['=', 'article_id', $get['article_id']]])->update(['is_del' => $get['is_del']]);
        if ($code > 0) {
            error::_plainError(['message' => '修改成功']);
        }
        error::_plainError(['message' => '修改失败']);
    }

    public function actionAddImage(){
        $file=$_FILES['file'];
        $path=DATA.DR."images/cms";
        $file_name=date("YmdHis").".".rand(1000,9999).'.jpg';
        $file_path=$path."/".$file_name;
        echo $file_path.PHP_EOL;
        if (move_uploaded_file($file["tmp_name"],$file_path)){
            error::_plainError(['code' =>200,'file_path'=>$file_path],true);
        }
        error::_plainError(['code' =>400,'message'=>'上传失败'],true);
    }
}